package com.example.administrator.food.modle.home.adapter;/**
 * Created by Administrator on 2016/9/27.
 */

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.administrator.food.modle.home.bean.Home;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * User: 张莉璟(2283465007@qq.com)
 * Date: 2016/09/27
 * Time: 22:02
 * progject: YueFoodHome
 * Describe： 首页头部轮播适配器
 */
public class XbannerAdapter extends PagerAdapter {
    private Context context;
    private List<Home.DatasBean.BannerBean> data;
    private String entityId;

    public XbannerAdapter(Context context, List<Home.DatasBean.BannerBean> data, String entityId) {
        this.context = context;
        this.data = data;
        this.entityId = entityId;
    }

    @Override
    public int getCount() {
        return data!=null?data.size():0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View ret = null; //定义一个视图
        //Home home = data.get(position);
        Home.DatasBean.BannerBean bean = data.get(position);
        ImageView image = new ImageView(context);
        image.setLayoutParams(new ViewGroup.LayoutParams
                (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        image.setScaleType(ImageView.ScaleType.FIT_XY);
        //字符串拼接
        String s = bean.getAdvertUrl();
        String arr[] =  s.split("=");
        String entityIdByJson = arr[1];
        String entityId = new String();
        try {
            JSONObject jsonObject = new JSONObject(entityIdByJson);
            entityId =  jsonObject.getString("entityId");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Picasso.with(context).load(entityId).into(image);
        //手动添加到container
        ret = image;
        container.addView(ret);
        return ret;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        if (object instanceof View) {
            View object1 = (View) object;
            container.removeView(object1);
        }
    }
}